#include "MeshFactory.h"
#include "BoxMesh.h"
#include "RobotMesh.h"
#include "../Core/Rect2.h"
#include "../Core/Point2.h"
#include "../Core/Vector2.h"
#include "../Core/Transform.h"
#include <algorithm>
#include "../Core/glPlatform.h"

namespace Model {
	namespace {
		std::shared_ptr<GLUquadric> makeQuadric() {
			return std::shared_ptr<GLUquadric>( gluNewQuadric(), gluDeleteQuadric );
		}
	}

	MeshFactory::~MeshFactory() {
	}

	
	std::shared_ptr<Mesh> createRobot( const Core::Transform3_t<float>& t ) {
		return std::shared_ptr<Mesh>( new RobotMesh(t) );
	}

	std::shared_ptr<Mesh> MeshFactory::createBox( const Core::Transform3_t<float>& t, const Core::Vector3_t<float>& dimensions ) {
		std::shared_ptr<BoxMesh> m = std::shared_ptr<BoxMesh>( new BoxMesh );
		m->mTransform = t;
		m->mDimensions = dimensions;

		return m;
	}
	
	std::shared_ptr<Mesh> MeshFactory::createTable( 
			const Core::Transform3_t<float>& t, 
			const Core::Vector3_t<float>& dimensions,
			float thickness,
			const Core::Vector2_t<float>& legDimensions,
			Core::Vector2_t<float>& legSeparation ) {
		using namespace Core;
		std::shared_ptr<Mesh> ptr( new Mesh );
		ptr->mTransform = t;

		// Table top
		ptr->mSubmeshes.push_back(
			createBox( Transform3f( Point3f(0, dimensions.y-thickness/2, 0) ), Vector3f( dimensions.x, thickness, dimensions.z ) )
		);

		// Table legs
		float legHeight = dimensions.y - thickness;
		Rect2f::fromCenterSize( 0, 0, dimensions.x - legSeparation.x - legDimensions.x, dimensions.z - legSeparation.y - legDimensions.y).eachCorner(
			[&] ( const Point2f& pt ) {
				using namespace Core;
				ptr->mSubmeshes.push_back(
					createBox( Transform3f( Point3f(pt.x, legHeight/2, pt.y)), Vector3f(legDimensions.x, legHeight, legDimensions.y) )
				);
			}
		);

		return ptr;
	}

}